app.controller('CheckinCtrl', [
		'$scope',
		'$q',
		'apiService',
		function(scope, $q, apiService) {
			scope.siginDateList = [];
			scope.todayStatus = false;
			scope.memberLoading = true;
			scope.running=false;
			var today = new Date().getDate();
			var init = function() {
				$('.calendar2').calendar({
					"onSelect" : function() {
						rend();
					}
				});
				loadMember();
			};

			var loadMember = function() {
				apiService.get("/api/member").then(
						function(resp) {
							if (resp && resp.data && resp.data.meta
									&& resp.data.meta.success) {
								scope.member = resp.data.data;
								loadMonthCheckins();
							} else {
								showMsg("请先完成注册或绑定");
								scope.memberLoading = false;
							}
						}, function(error) {
							showMsg("系统正忙，请稍后再试");
							scope.memberLoading = false;
						});

			};

			var loadMonthCheckins = function() {
				apiService.get('/signin/list').then(function(res) {
					if (res && res.data && res.data.siginDateList) {
						scope.siginDateList = res.data.siginDateList;
						rend();
					}
					scope.memberLoading = false;
				}, function(error) {
					scope.memberLoading = false;
				});

			};

			var firstMonday = new Date(new Date().getFullYear() + '-'
					+ (new Date().getMonth() + 1) + '-01').getDay();
			var rend = function() {
				if (scope.siginDateList && scope.siginDateList.length) {
					scope.siginDateList.forEach(function(day) {
						var con = ".calendar table td[data-id='"
								+ (day - 1 + firstMonday) + "']";
						$(con).addClass("signed");
						if (day == today) {
							scope.todayStatus = true;
						}
					})
				}
			};

			scope.checkin = function() {
				if (scope.memberLoading) {
					return;
				}
				if (!scope.member) {
					showMsg("请先完成注册或绑定");
					return;
				}
				if(scope.running){
					return;
				}
				scope.running=true;
				apiService.get('/signin').then(function(res) {
					if (res && res.data.success) {
						loadMonthCheckins();
						showMsg("签到成功");
						scope.running=false;
					} else {
						if (res.data && res.data.message) {
							showMsg("签到失败：" + res.data.message);
						} else {
							showMsg("系统忙，请稍后再试");
						}
						scope.running=false;
					}
				}, function(error){
					running = false;
				});
			};

			init();

			var showMsg = function(msg) {
				$("#msg").html(msg);
				if ($('.alert').hasClass('hide')) {
					$('.alert').removeClass('hide');
				}
			};

		} ]);

$('.alert button').click(function() {
	if (!$('.alert').hasClass('hide')) {
		$('.alert').addClass('hide');
	}
});
